import { useState, useEffect } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "./ui/table";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { Input } from "./ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import { AlertTriangle, Clock, Eye, Search, Filter, X, Zap, Database } from "lucide-react";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "./ui/dialog";
import { Textarea } from "./ui/textarea";
import { useI18n } from "../lib/i18n/context";
import { useDataSource } from "../lib/data/context";
import { toast } from "sonner@2.0.3";

interface SlowQuery {
  id: string;
  query: string;
  database: string;
  duration: number;
  timestamp: string;
  rowsExamined: number;
  rowsSent: number;
  lockTime: number;
  user: string;
  host: string;
  severity: 'low' | 'medium' | 'high' | 'critical';
}

const mockSlowQueries: SlowQuery[] = [
  {
    id: '1',
    query: 'SELECT * FROM users u JOIN orders o ON u.id = o.user_id WHERE u.created_at > "2024-01-01" ORDER BY u.id',
    database: 'production-db',
    duration: 15.234,
    timestamp: '2024-12-15 14:32:15',
    rowsExamined: 2500000,
    rowsSent: 1500,
    lockTime: 0.001,
    user: 'app_user',
    host: '192.168.1.100',
    severity: 'high'
  },
  {
    id: '2',
    query: 'UPDATE inventory SET quantity = quantity - 1 WHERE product_id IN (SELECT id FROM products WHERE category = "electronics")',
    database: 'inventory-db',
    duration: 8.765,
    timestamp: '2024-12-15 14:30:22',
    rowsExamined: 850000,
    rowsSent: 0,
    lockTime: 2.145,
    user: 'inventory_service',
    host: '192.168.1.101',
    severity: 'medium'
  },
  {
    id: '3',
    query: 'SELECT COUNT(*) FROM analytics_events WHERE event_date BETWEEN "2024-01-01" AND "2024-12-31" GROUP BY event_type',
    database: 'analytics-db',
    duration: 32.156,
    timestamp: '2024-12-15 14:28:45',
    rowsExamined: 5600000,
    rowsSent: 25,
    lockTime: 0.003,
    user: 'analytics_user',
    host: '192.168.1.102',
    severity: 'critical'
  },
  {
    id: '4',
    query: 'DELETE FROM temp_logs WHERE created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)',
    database: 'logs-db',
    duration: 4.234,
    timestamp: '2024-12-15 14:25:12',
    rowsExamined: 125000,
    rowsSent: 0,
    lockTime: 1.234,
    user: 'cleanup_job',
    host: '192.168.1.103',
    severity: 'low'
  }
];

const severityColors = {
  low: 'bg-green-500',
  medium: 'bg-yellow-500',
  high: 'bg-orange-500',
  critical: 'bg-red-500'
};

export function SlowQueryMonitor() {
  const { t } = useI18n();
  const { slowQueries, databases, fetchSlowQueries, killQuery, optimizeQuery, isLoading } = useDataSource();
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedInstance, setSelectedInstance] = useState<string>('');
  const [selectedSeverity, setSelectedSeverity] = useState('all');

  useEffect(() => {
    if (selectedInstance) {
      fetchSlowQueries();
    }
  }, [selectedInstance]);

  const handleKillQuery = async (queryId: string) => {
    try {
      await killQuery(queryId);
      toast.success('Query killed successfully');
    } catch (error) {
      console.error('Failed to kill query:', error);
    }
  };

  const handleOptimizeQuery = async (queryId: string) => {
    try {
      const result = await optimizeQuery(queryId);
      toast.success(`Optimization suggestions: ${result.suggestions.join(', ')}`);
    } catch (error) {
      console.error('Failed to optimize query:', error);
    }
  };

  const selectedDb = databases.find(db => db.id === selectedInstance);

  const filteredQueries = selectedInstance ? slowQueries.filter(query => {
    const matchesSearch = query.query.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         query.user.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesInstance = query.database === selectedDb?.name;
    const matchesSeverity = selectedSeverity === 'all' || query.severity === selectedSeverity;
    
    return matchesSearch && matchesInstance && matchesSeverity;
  }) : [];

  const formatDuration = (duration: number) => {
    if (duration === undefined || duration === null) return '0.000s';
    return `${duration.toFixed(3)}s`;
  };

  const formatNumber = (num: number) => {
    if (num === undefined || num === null) return '0';
    return num.toLocaleString();
  };

  const truncateQuery = (query: string, maxLength: number = 80) => {
    return query.length > maxLength ? query.substring(0, maxLength) + '...' : query;
  };

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <AlertTriangle className="h-5 w-5 text-orange-600" />
              <CardTitle>{t.slowQueries.title}</CardTitle>
            </div>
            {selectedInstance && (
              <Badge variant="destructive">
                {filteredQueries.length} slow queries detected
              </Badge>
            )}
          </div>

        </CardHeader>
        <CardContent>
          <div className="flex flex-col sm:flex-row gap-4 mb-6">
            <Select value={selectedInstance} onValueChange={setSelectedInstance}>
              <SelectTrigger className="w-full sm:w-[250px]">
                <SelectValue placeholder={t.slowQueries.chooseDatabase} />
              </SelectTrigger>
              <SelectContent>
                {databases.map(db => (
                  <SelectItem key={db.id} value={db.id}>
                    {db.name} ({db.status})
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
            {selectedInstance && (
              <>
                <div className="flex-1">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                    <Input
                      placeholder="Search queries or users..."
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      className="pl-10"
                    />
                  </div>
                </div>
                <Select value={selectedSeverity} onValueChange={setSelectedSeverity}>
                  <SelectTrigger className="w-[150px]">
                    <SelectValue placeholder="All severities" />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="all">All severities</SelectItem>
                    <SelectItem value="low">Low</SelectItem>
                    <SelectItem value="medium">Medium</SelectItem>
                    <SelectItem value="high">High</SelectItem>
                    <SelectItem value="critical">Critical</SelectItem>
                  </SelectContent>
                </Select>
              </>
            )}
          </div>

          {!selectedInstance ? (
            <div className="text-center py-12">
              <Database className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
              <h3 className="text-lg font-medium mb-2">{t.performance.selectInstance}</h3>
              <p className="text-muted-foreground">
                Choose a database instance from the dropdown above to view its slow queries
              </p>
            </div>
          ) : (
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t.slowQueries.table.impact}</TableHead>
                    <TableHead>{t.slowQueries.table.query}</TableHead>
                    <TableHead>{t.slowQueries.table.database}</TableHead>
                    <TableHead>{t.slowQueries.table.duration}</TableHead>
                    <TableHead>Rows Examined</TableHead>
                    <TableHead>Lock Time</TableHead>
                    <TableHead>User</TableHead>
                    <TableHead>{t.slowQueries.table.timestamp}</TableHead>
                    <TableHead>{t.slowQueries.table.actions}</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filteredQueries.length === 0 ? (
                    <TableRow>
                      <TableCell colSpan={9} className="text-center py-8">
                        <div className="flex flex-col items-center space-y-3">
                          <AlertTriangle className="h-8 w-8 text-muted-foreground" />
                          <p className="text-muted-foreground">No slow queries found</p>
                          {(searchTerm || selectedSeverity !== 'all') && (
                            <p className="text-sm text-muted-foreground">
                              Try adjusting your search filters
                            </p>
                          )}
                        </div>
                      </TableCell>
                    </TableRow>
                  ) : (
                  filteredQueries.map(query => (
                    <TableRow key={query.id}>
                      <TableCell>
                        <Badge 
                          variant="secondary" 
                          className={`${severityColors[query.severity || 'low']} text-white capitalize`}
                        >
                          {query.severity === 'low' ? t.slowQueries.impact.low :
                           query.severity === 'medium' ? t.slowQueries.impact.medium :
                           query.severity === 'high' ? t.slowQueries.impact.high :
                           t.slowQueries.impact.high}
                        </Badge>
                      </TableCell>
                      <TableCell className="max-w-md">
                        <code className="text-xs bg-muted px-2 py-1 rounded block whitespace-pre-wrap break-words">
                          {query.query || ''}
                        </code>
                      </TableCell>
                      <TableCell>{query.database || '-'}</TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-1">
                          <Clock className="h-3 w-3" />
                          <span>{formatDuration(query.duration)}</span>
                        </div>
                      </TableCell>
                      <TableCell>{formatNumber(query.rowsExamined)}</TableCell>
                      <TableCell>{formatDuration(query.lockTime)}</TableCell>
                      <TableCell>{query.user || '-'}</TableCell>
                      <TableCell>{query.timestamp || '-'}</TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Dialog>
                            <DialogTrigger asChild>
                              <Button variant="ghost" size="sm">
                                <Eye className="h-4 w-4" />
                              </Button>
                            </DialogTrigger>
                          <DialogContent className="max-w-3xl">
                            <DialogHeader>
                              <DialogTitle>Query Details</DialogTitle>
                            </DialogHeader>
                            <div className="space-y-4">
                              <div className="grid grid-cols-2 gap-4">
                                <div>
                                  <label className="text-sm font-medium">Database</label>
                                  <p>{query.database || '-'}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium">User</label>
                                  <p>{query.user || '-'}@{query.host || '-'}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium">Duration</label>
                                  <p>{formatDuration(query.duration)}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium">Severity</label>
                                  <Badge className={`${severityColors[query.severity || 'low']} text-white capitalize`}>
                                    {query.severity || 'low'}
                                  </Badge>
                                </div>
                                <div>
                                  <label className="text-sm font-medium">Rows Examined</label>
                                  <p>{formatNumber(query.rowsExamined)}</p>
                                </div>
                                <div>
                                  <label className="text-sm font-medium">Rows Sent</label>
                                  <p>{formatNumber(query.rowsSent)}</p>
                                </div>
                              </div>
                              <div>
                                <label className="text-sm font-medium">Full Query</label>
                                <Textarea 
                                  value={query.query || ''} 
                                  readOnly 
                                  className="mt-2 h-32 font-mono text-sm"
                                />
                              </div>
                            </div>
                          </DialogContent>
                          </Dialog>
                          <Button 
                            variant="ghost" 
                            size="sm" 
                            onClick={() => handleOptimizeQuery(query.id)}
                            disabled={isLoading}
                          >
                            <Zap className="h-4 w-4" />
                          </Button>
                          <Button 
                            variant="ghost" 
                            size="sm" 
                            onClick={() => handleKillQuery(query.id)}
                            disabled={isLoading}
                          >
                            <X className="h-4 w-4" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                  )}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}